<?

require_once('sql/sql_profile.php');

define('TPL_LOGIN', 'account_login.tpl');
define('TPL_REGISTER', 'account_new.tpl');

class Session {
    private $smarty;
    private $sql_profile;

    public function __construct($smarty, $mysql_link) {
        $this->smarty      = $smarty;
        $this->profile = new Sql_profile($mysql_link);
    }

    public function show_login_form() {
        return TPL_LOGIN;
    }

    public function show_registration($user = null) {
        if (!is_null($user))
            $this->smarty->assign('user', $user);

        return TPL_REGISTER;
    }

    ##
    # Register a new account.
    public function register($user, $pass, $pass_again) {
        $user = strtolower(htmlspecialchars($user));

        if ($pass != $pass_again) {
            $this->smarty->assign('no_match', true);
            return $this->show_registration($user);
        }

        $succs = $this->profile->create_user(
            $user, crypt($pass), $_SERVER['REMOTE_ADDR']);
        if (!$succs) {
            $this->smarty->assign('user_in_use', true);
            return $this->show_registration($user);
        }

        $_SESSION['user'] = $user;
        $this->smarty->assign('logged_in', true);
        $this->smarty->assign('registration_complete', true);
        return $this->show_registration($user);
    }

    public function logout() {
        unset($_SESSION['user']);
        session_destroy();
        $this->smarty->assign('logged_in', false);
        return $this->show_login_form();
    }

    public function login($user, $pass) {
        //login attempt
        $db_pass = $this->profile->get_password($user);
        $user = strtolower(htmlspecialchars($user));

        if (crypt($pass, $db_pass) == $db_pass) {
            $this->smarty->assign('logged_in', true);
            $this->smarty->assign('succs_login', true);
            $_SESSION['user'] = $user;
        }
        else {
            $this->smarty->assign('failed_login', true);
        }
        
        return $this->show_login_form();
    }
}

    ?>
